package handlers

import (
	"errors"
	"fmt"
	"html/template"
	"strings"

	"github.com/yjp211/web"

	"mutu/misc/conf"
	"mutu/misc/typedef"
	"mutu/models"
	"mutu/service"
)

type AuthView struct{}

var (
	AuthHandler   = AuthView{}
	SessionExpire = conf.GetInt("SessionExpire", 3600)
)

func (p AuthView) Index(ctx *web.Context) {
	data := typedef.Dict{}
	t, _ := template.ParseFiles("templates/login.html")
	t.Execute(ctx, data)
}

func (p AuthView) SaveSessionCookie(sessionid string, live int, ctx *web.Context) {

	buf := fmt.Sprintf("%s=%s;  path=/; max-age=%d", conf.SessionKey, sessionid, live)
	ctx.Header().Set("Set-Cookie", buf)
}

func (p AuthView) OauthUrl(ctx *web.Context) string {
	way, ok := ctx.Params["way"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	way = strings.ToLower(way)
	data, err := service.AuthService.GetOauthUrl(ctx.Request.Host, way)
	return JsonpReturn(ctx, data, err)
}

func (p AuthView) CallBack(ctx *web.Context) string {
	way, ok := ctx.Params["state"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	code, ok := ctx.Params["code"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	data, err := service.AuthService.CallBack(ctx.Request.Host, way, code)
	if err != nil {
		return JsonpReturn(ctx, data, err)
	}
	ticket := data["ticket"].(string)
	live := data["live"].(int)
	p.SaveSessionCookie(ticket, live, ctx)
	l := fmt.Sprintf("/auth/jump?ticket=%s", ticket)
	ctx.Redirect(302, l)
	return ""

}

func (p AuthView) OauthJump(ctx *web.Context) {
	t, _ := template.ParseFiles("templates/oauth-jump.html")
	t.Execute(ctx, nil)
}

func (p AuthView) PasswdLogin(ctx *web.Context) string {
	email, ok := ctx.Params["email"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	passwd, ok := ctx.Params["passwd"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	data, err := service.AuthService.PasswdLogin(email, passwd)
	if err == nil {
		ticket := data["ticket"].(string)
		live := data["live"].(int)
		p.SaveSessionCookie(ticket, live, ctx)
	}
	return JsonpReturn(ctx, data, err)
}

func (p AuthView) OauthInfo(ctx *web.Context) string {
	data := typedef.Dict{
		"ses": ctx.Dict["session"].(*models.Session),
	}
	return JsonpReturn(ctx, data, nil)
}

func (p AuthView) Logout(ctx *web.Context) string {
	ses := ctx.Dict["session"].(*models.Session)

	err := service.SessionService.RemoveSession(ses)

	return JsonpReturn(ctx, nil, err)
}
